/**
 * 寻找并合并数组中连续的1和2的区间
 * @param arr 输入的数组，包含数字1和2
 * @returns 返回两个数组，分别包含合并后的连续1和连续2的区间，且区间长度大于等于8
 */
export const findConsecutiveOnes = (arr: number[]): any=> {
    // 存储连续1的起始和结束索引
    const result1: [number, number][] = [];
    // 存储连续2的起始和结束索引
    const result2: [number, number][] = [];
    let i = 0;

    // 遍历数组，寻找连续的1和2的区间
    while (i < arr.length) {
        // 当遇到1时，记录连续1的起始索引
        if (arr[i] === 1) {
            const start = i;
            // 继续向前寻找，直到遇到非1元素，记录连续1的结束索引
            while (i < arr.length && arr[i] === 1) {
                i++;
            }
            const end = i - 1;
            // 将连续1的区间添加到result1数组中
            result1.push([start, end]);
        // 当遇到2时，记录连续2的起始索引
        } else if (arr[i] === 2) {
            const start = i;
            // 继续向前寻找，直到遇到非2元素，记录连续2的结束索引
            while (i < arr.length && arr[i] === 2) {
                i++;
            }
            const end = i - 1;
            // 将连续2的区间添加到result2数组中
            result2.push([start, end]);
        } else {
            // 遇到非1非2的元素时，继续向后寻找
            i++;
        }
    }

    // 合并连续1的区间
    const merge_result1 = mergeIntervals(result1)
    // 合并连续2的区间
    const merge_result2 = mergeIntervals(result2)

    // 过滤合并后的连续1的区间，只保留区间长度大于等于10的区间
    const filter_merge_result1= merge_result1.filter(arr => arr[1]-arr[0] >= 10)
    // 过滤合并后的连续2的区间，只保留区间长度大于等于10的区间
    const filter_merge_result2 = merge_result2.filter(arr => arr[1] - arr[0] >= 10)

    // 返回过滤后的合并结果
    return [filter_merge_result1, filter_merge_result2]
}

function mergeIntervals(intervals: [number, number][]): [number, number][] {
    if (!intervals.length) {
        return [];
    }

    // Sort the intervals based on the start time
    intervals.sort((a, b) => a[0] - b[0]);

    const merged: [number, number][] = [intervals[0]];

    for (let i = 1; i < intervals.length; i++) {
        const lastMerged = merged[merged.length - 1];
        const current = intervals[i];

        // If the current interval overlaps with the last merged one, merge them
        if (current[0] - lastMerged[1] < 2) {
            merged[merged.length - 1] = [lastMerged[0], Math.max(lastMerged[1], current[1])];
        } else {
            // Otherwise, add the current interval to the list of merged intervals
            merged.push(current);
        }
    }

    return merged;
}



